import { Injectable, NestMiddleware } from '@nestjs/common';
import { CryptoService } from 'src/modules/crypto/crypto.service';

@Injectable()
// 导出HashPasswordMiddleware类，实现NestMiddleware接口
export class HashPasswordMiddleware implements NestMiddleware {
  // 构造函数，注入CryptoService服务
  constructor(private readonly cryptoService: CryptoService) {}
  // 实现use方法，用于处理请求
  use(req: any, res: any, next: () => void) {
    // 获取请求体中的密码
    let pwd = req.body.password;
    // 如果密码存在
    if (pwd) {
      // 获取加密所需的盐值
      const salt = this.cryptoService.salt;
      const entireSalt = this.cryptoService.getEntireSalt(salt);
      // 对密码进行加密，并将加密后的密码和盐值添加到请求体中
      req.body['password'] = this.cryptoService.encrypt(pwd, entireSalt);
      req.body['salt'] = salt;
    }
    // console.log(req.body);
    // 调用next方法，继续处理请求
    next();
  }
}
